var FromEngine = new FromEngine()
/**
 * 表单工具
 */
function FromEngine(){
	var that = this; 
	
	/**
	 * 表单验证和提交
	 * @param fromObj
	 * 验证表单对象
	 * @param rules
	 * 验证规则
	 * @param messages
	 * 验证提示消息
	 * @param url
	 * 表单提交地址
	 * @return
	 * 返回验证器,可操作验证器,设置验证规则
	 */
	that.validateForm = function(fromObj,rules,messages,url){
		return $(fromObj).validate({
			rules: $.extend({},rules),
			messages:$.extend({},messages),
		    errorClass: "error",
		    success: 'valid',
		    errorPlacement: function (error, element) {
		    	if(error[0].innerText!=''&&error[0].innerText!=null){
		    		
		    		layer.tips(error[0].innerText,element,{//1.错误信息，2提示位置，3同时提示多个错误
		                tipsMore:true,//错误信息可以同时提示多个，...
		                tips: [2, 'rgb(237, 85, 84)']
		            });
		    	}
		    },
		    submitHandler: function (form) {
		        $(form).ajaxSubmit({
					type: 'post',  
					dataType: "json",
		            url: url,
		            success:function( data ){
		                if ( data.stutas == "success" ) {
		                	layer.msg('成功', {icon: 1});
		                	// 仅在弹出层时成功操作后要求强制刷新父页面才如此做
		                	try {
		                		parent.layer.close(parent.index);
			                	parent.window.location.href = parent.window.location.href;
							} catch (e) {}
		                } else {
		                	layer.msg('异常', {icon: 2});
		                }
		            }
				});
		    }
		});
	}

	/**
	 * 表单数据绑定
	 * @param formId
	 * 表单ID
	 * @param jsonData
	 * 表单数据JSON
	 */
	that.jsonBindForm = function(formId, jsonData) {
		this.formId = formId;
		$(formId)[0].reset();
		if (jsonData != null && jsonData != '' && jsonData != 'undefined') {
			var elements = $(formId)[0].elements;
			if (elements.length > 0) {
				var layerIndex = layer.load(2,{time: 10*1000,shade: [0.6,'#fff'],shadeClose : true});
				for (var i = 0; i < elements.length; i++) {
					var ele = $(elements[i]),
						eleName = elements[i].name,
						eleType = elements[i].type.toString().toLowerCase(),
						jsonv =  jsonData[eleName];
					if (eleType == 'text' || eleType == 'textarea' || eleType == 'password' || eleType == 'hidden') {
						if (jsonv != 'null' && jsonv != null && jsonv != 'undefined') {
							elements[i].value = jsonv;
						} else {
							elements[i].value = '';
						}
					}
					if (eleType == 'checkbox') {
						var feles = document.getElementsByName(eleName);
						if(jsonv+""!="undefined"){
							if (jsonv.indexOf(',') != -1) {
								var s = jsonv.split(',');
							}else{
								var s = new Array();
								s[0] = jsonv;
							}
							for (var j = 0; j < feles.length; j++) {
								for (var k = 0; k < s.length; k ++) {
									if (feles[j].value == s[k]) feles[j].checked = true;
								}
							}
						}
					}
					if (eleType == 'radio') {
						var feles = document.getElementsByName(eleName);
						for (var j = 0; j < feles.length; j++) {
							if (feles[j].value == jsonv) feles[j].checked = true;
						}
					}
					
					// TODO SELECT
					if (ele.is('select') && jsonv && !ComUtil.isEmpty(jsonv)) {
						if (ele.attr('multiple')) {
							ComUtil.chosenUpdate(ele.attr('id') ? ('#' +ele.attr('id')) : ('select[name='+eleName+']'), jsonv.split(','), true);
						} else {
							ele.val(jsonv);
						}
					}
				}
				//if (elements[0].style.display != 'none' && elements[0].disabled!=true) {elements[0].focus();}
				layer.close(layerIndex);
			}
		}
	}
	
	/**
	 * 验证表单和提交表单
	 * @param fromObj
	 * 验证表单form
	 * @param options
	 * 验证配置项
	 * @return
	 * 返回验证器,可操作验证器,设置验证规则
	 */
	that.vsFrom = function(fromObj, options){
		var isUrl = typeof (options.cfgUrlOrFunction) === "string", 
			isFunction = !isUrl && typeof (options.cfgUrlOrFunction) === "function";
		//alert(options.data.data);
		options = $.extend({},{
			debug: false,
			errorClass: "error",
		    success: 'valid',
		    errorPlacement: function (error, element) {// 错误提示样式
		    	if(error[0].innerText!=''&&error[0].innerText!=null){
		    		layer.tips(error[0].innerText,element,{//1.错误信息，2提示位置，3同时提示多个错误
		                tipsMore:true,//错误信息可以同时提示多个，...
		                tips: [2, 'rgb(237, 85, 84)']
		            });
		    	}
		    },
		    submitHandler: function (form) {
		    	if (!!options.debug) {
		    		return;
		    	}
		    	if (isUrl) {
		    		 var index = layer.load(2,{time: 10*1000,shade: [0.6,'#fff'],shadeClose : true});
		    		 $(form).ajaxSubmit({
						type: 'post',  
						dataType: "json",
						beforeSerialize:function(){
							if (options.beforeSubmitFunction && typeof (options.beforeSubmitFunction) === "function") {
		                		options.beforeSubmitFunction();
		                	}
						},
			            url: options.cfgUrlOrFunction,
			            success: function(data){
			                if (data.stutas == "success") {
			                	// 处理成功后的回调函数
			                	if (options.cfgCallBack && typeof (options.cfgCallBack) === "function") {
			                		options.cfgCallBack(data);
			                	}
			                	layer.msg('成功', {icon: 1});
			                } else {
			                	if(data.message){
			                		layer.msg(data.message, {icon: 2});
			                	}else{
			                		layer.msg('异常', {icon: 2});
			                	}
			                	
			                }
			                layer.close(index);
			            }
					});
		    	} else if(isFunction) {
		    		options.cfgUrlOrFunction();
		    	}
		    }
		}, options);
		return $(fromObj).validate(options);
	}
}